package com.mrjy.common.util;

import com.mrjy.activity.bo.IActivityInfoBo;
import com.mrjy.activity.dto.ActivityDTO;
import com.mrjy.activity.dto.ActivityInfoDTO;
import com.mrjy.common.entity.ActivityInfo;
import com.mrjy.common.entity.DiyVideoInfo;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.schooldiy.dao.IDiyVideoDao;
import com.mrjy.schooldiy.dto.DiyVideoInfoDTO;
import com.mrjy.video.bo.IVideoInfoBo;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * redis缓存工具类
 * @author Administrator
 *
 */
public class RedisUtil {
	
	private static RedisPool redisPool;
	private static IVideoInfoBo videoInfoBo;
	private static IActivityInfoBo activityInfoBo;
	private static Logger logger = Logger.getLogger(RedisUtil.class);
	private static IDiyVideoDao diyVideoDao;
	static{
		redisPool = (RedisPool) SpringContextHelper.getBean("poolJedisClient");
		videoInfoBo = (IVideoInfoBo)SpringContextHelper.getBean("videoInfoBo");
		activityInfoBo = (IActivityInfoBo)SpringContextHelper.getBean("activityInfoBo");
	}
	
	/**
	 * 查询视频/音频缓存
	 * @param videoId
	 * @return
	 */
	public static PolyInfo cache(String videoId) {
        if (StringUtils.isBlank(videoId) || "null".equals(videoId)) {
            return null;
		}
		//先去缓存中查
		String polyInfoJson = "";
        polyInfoJson = redisPool.get(GlobalConstant.VIDEO_POLYV_URL + videoId);
        PolyInfo polyInfo = new PolyInfo();
        if (StringUtils.isBlank(polyInfoJson)) {  //缓存中查不到,就调保利威视api查
            VideoInfo info = (VideoInfo) videoInfoBo.queryById(Integer.parseInt(videoId));
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(info.getVideoCode());
			PolyInfo polyInfoAudio = (PolyInfo) PolyvUtil.queryUrlByVid(info.getAudioCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setSeed(polyInfoVideo.getSeed());
                polyInfo.setDuration(polyInfoVideo.getDuration());
            }
            if (polyInfoAudio != null && polyInfoAudio.getMp3().indexOf(".mp3") > -1) {
                polyInfo.setDuration(polyInfoAudio.getDuration());
				polyInfo.setMp3(polyInfoAudio.getMp3());
				polyInfo.setSourceFilesize(polyInfoAudio.getSourceFilesize());
				polyInfo.setTitle(polyInfoAudio.getTitle());
			}
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
            //暂时关闭保存
            redisPool.set(GlobalConstant.VIDEO_POLYV_URL + info.getId(), polyInfoJson);  //存入redis
            logger.debug("##############Query From PolyV###############");
        }else {
			polyInfo = (PolyInfo) JSONObject.toBean(JSONObject.fromObject(polyInfoJson), PolyInfo.class);
		}
		return  polyInfo;
	}

    /**
     * 查询token
     *
     * @param videoId
     * @param params
     * @return
     */
    public static String cache(String videoId, String URL, Map<String, String> params) {
        //1.判断时间先，如果五分钟内，则直接从pool里面返回token
        //先去缓存中查，得到时间
        String key = GlobalConstant.VIDEO_POLYV_TOKEN + videoId;
        String cache_token_json = redisPool.get(key);
        if (StringUtils.isNotBlank(cache_token_json)) {
            JSONObject cache_jsonObject = JSONObject.fromObject(cache_token_json);
            String ts = cache_jsonObject.getString("ts");
            String token = cache_jsonObject.getString("token");

            long save_ts = Long.parseLong(ts);
            long now_ts = Long.parseLong(params.get("ts"));
            //如果分钟少于4.30，则重新的到新的token，否则就返回token回去
            long gap_seconds = (now_ts - save_ts) / 1000;

            if (4 * 60 + 30 > gap_seconds) {
                //4.30 内
                return token;
            } else {
                //重新请求新的token
                String json = HttpUtil.doPost(URL, params);
                if (StringUtils.isBlank(json)) {
                    return "";
                } else {
                    JSONObject save_object = new JSONObject();
                    JSONObject empty_jsonObject = JSONObject.fromObject(json);
                    JSONObject data = (JSONObject) empty_jsonObject.get("data");
                    String new_ts = data.getString("createdTime");
                    String token1 = data.getString("token");
                    save_object.put("ts", new_ts);
                    save_object.put("token", token1);
                    redisPool.set(key, save_object.toString());
                    return token1;
                }
            }
        } else {
            //空的就放token进去,data可能为空,token 还需要保存起来
            String json = HttpUtil.doPost(URL, params);
            if (StringUtils.isBlank(json)) {
                return "";
            } else {
                JSONObject save_object = new JSONObject();
                JSONObject empty_jsonObject = JSONObject.fromObject(json);
                JSONObject data = (JSONObject) empty_jsonObject.get("data");
                String ts = data.getString("createdTime");
                String token1 = data.getString("token");
                save_object.put("ts", ts);
                save_object.put("token", token1);
                redisPool.set(key, save_object.toString());
                return token1;
            }
        }
    }



	/**
	 * 判断用户是否拥有该视频的观看权限
	 * @param userId
	 * @param videoId
	 * @return true:有  false:没有
	 */
	public static Boolean isVideoVip(Integer userId,Integer videoId) {
        //用户能观看的所有视频id   格式如:8,9,11,137
        String videoIds = redisPool.get(GlobalConstant.USER_VIDEO_VIP + userId);
        if (StringUtils.isBlank(videoIds) || userId == null || userId == 0
        		||videoId == null|| videoId ==0) {
			return false;
		}
		String[] split = videoIds.split(",");
		for (String s : split) {
			if (s.equals(videoId.toString())) {
				return true;
			}
		}
		return false;
	}

	public static PolyInfo cacheActivityVideo(String videoId) {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(videoId) || "null".equals(videoId)) {
            return null;
		}
		//先去缓存中查
		String polyInfoJson = "";
        polyInfoJson = redisPool.get(GlobalConstant.VIDEO_ACTIVITY_POLYV_URL + videoId);
        PolyInfo polyInfo = new PolyInfo();
        if (StringUtils.isBlank(polyInfoJson)) {  //缓存中查不到,就调保利威视api查
        	ActivityInfoDTO info =  activityInfoBo.queryActivityById(Integer.parseInt(videoId));
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(info.getVideoCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setDuration(polyInfoVideo.getDuration());
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
            //暂时关闭保存
            redisPool.set(GlobalConstant.VIDEO_ACTIVITY_POLYV_URL + info.getId(), polyInfoJson);  //存入redis
            logger.debug("##############Query From PolyV###############");
        }else {
			polyInfo = (PolyInfo) JSONObject.toBean(JSONObject.fromObject(polyInfoJson), PolyInfo.class);
		}
		return  polyInfo;
	}
	public static PolyInfo cacheDIYVideoOrAudio(String videoId,String polyCode) {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(videoId) || "null".equals(videoId)) {
            return null;
		}
		//先去缓存中查
		String polyInfoJson = "";
        polyInfoJson = redisPool.get(GlobalConstant.VIDEODIY_POLYV_URL + videoId);
        PolyInfo polyInfo = new PolyInfo();
        if (StringUtils.isBlank(polyInfoJson)) {  //缓存中查不到,就调保利威视api查
        	DiyVideoInfo dto = new DiyVideoInfo();
        	try {
        		dto.setId(Integer.parseInt(videoId));
        	} catch (NumberFormatException e) {
        	    e.printStackTrace();
        	}
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(polyCode);
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setDuration(polyInfoVideo.getDuration());
                polyInfo.setMp3(polyInfoVideo.getMp3());
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
            //暂时关闭保存
            redisPool.set(GlobalConstant.VIDEODIY_POLYV_URL + Integer.parseInt(videoId), polyInfoJson);  //存入redis
            logger.debug("##############Query From PolyV###############");
        }else {
			polyInfo = (PolyInfo) JSONObject.toBean(JSONObject.fromObject(polyInfoJson), PolyInfo.class);
		}
		return  polyInfo;
	}

//    public static PolyvTokenUtil cache(String videoId, String userId) {
//        PolyvTokenUtil tokenUtil = null;
//        if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
//            return null;
//        }
//        //先去缓存中查
//        String polyInfoJson = "";
//        polyInfoJson = redisPool.get("vid_token_" + videoId);
//        if (StringUtils.isBlank(polyInfoJson)) {  //缓存中查不到,就调保利威视api查
//            tokenUtil = new PolyvTokenUtil(videoId,
//                    Util.getHostIp(Util.getInetAddress()),
//                    userId, "123", "123");
//            polyInfoJson = JSONObject.fromObject(tokenUtil).toString();
//            redisPool.set("vid_token_" + videoId, polyInfoJson);  //存入redis
//            logger.debug("##############Query From PolyV###############");
//        } else {
//            //有可能是5分钟内的
//            tokenUtil = (PolyvTokenUtil) JSONObject.toBean(JSONObject.fromObject(polyInfoJson), PolyvTokenUtil.class);
//            long save_ts = tokenUtil.getTs();
//            long now_ts = System.currentTimeMillis();
//            //如果分钟少于4.30，则重新的到新的token，否则就返回token回去
//            long gap_seconds = (now_ts - save_ts) / 1000;
//
//            if (4 * 60 + 30 > gap_seconds) {
//                //4.30 内
//                return tokenUtil;
//            } else {
//                //重新产生新的token
//                tokenUtil = new PolyvTokenUtil(videoId,
//                        Util.getHostIp(Util.getInetAddress()),
//                        userId, "123", "123");
//                polyInfoJson = JSONObject.fromObject(tokenUtil).toString();
//                redisPool.set("vid_token_" + videoId, polyInfoJson);  //存入redis
//                logger.debug("##############Query From PolyV###############");
//            }
//        }
//        return tokenUtil;
//    }


}
